package com.messi.languagehelper;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.iflytek.speech.SpeechError;
import com.iflytek.speech.SynthesizerPlayer;
import com.iflytek.speech.SynthesizerPlayerListener;
import com.iflytek.ui.RecognizerDialogListener;
import com.iflytek.ui.SynthesizerDialog;
import com.iflytek.ui.v;
import com.messi.languagehelper.db.DataBaseUtil;
import com.messi.languagehelper.dialog.PopDialog;
import com.messi.languagehelper.dialog.PopDialog.PopViewItemOnclickListener;
import com.messi.languagehelper.util.ToastUtil;

public class RecordActivity extends Activity implements SynthesizerPlayerListener {
	
	private ListView record_listview;
	private ProgressBar record__progressbar;
	private TextView record_load_result;
	private Button top_btn;
	
	private RecordAdapter adapter;
	private List<NoteBean> beans;
	private DataBaseUtil mDataBaseUtil;
	
	private int offset;
	private int maxResult = 5000;
	
	private int btn_state = 0;//0是TOP_BTN_DEL，1是TOP_BTN_PLAY
	
	// 缓存，保存当前的引擎参数到下一次启动应用程序使用.
	private SharedPreferences mSharedPreferences;
	//合成对象.
	private SynthesizerPlayer mSynthesizerPlayer;
	//缓冲进度
	private int mPercentForBuffering = 0;
	//播放进度
	private int mPercentForPlaying = 0;
	//合成Dialog
	private SynthesizerDialog ttsDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.record_activity);
		init();
	}
	
	private void init(){
		record_listview = (ListView)findViewById(R.id.record_listview);
		record__progressbar = (ProgressBar)findViewById(R.id.record__progressbar);
		record_load_result = (TextView)findViewById(R.id.record_load_result);
		top_btn = (Button)findViewById(R.id.top_btn);
		beans = new ArrayList<NoteBean>();
		adapter = new RecordAdapter();
		record_listview.setAdapter(adapter);
		mDataBaseUtil = new DataBaseUtil(this);
		mSharedPreferences = getSharedPreferences(getPackageName(), MODE_PRIVATE);
		//初始化合成Dialog.
		ttsDialog = new SynthesizerDialog(this, "appid=" + getString(R.string.app_id));
		top_btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showMenu();
			}
		});
		
		beans = mDataBaseUtil.getDataList(offset, maxResult);
		adapter.notifyDataSetChanged();
		
	}

	
	class RecordAdapter extends BaseAdapter {

		private LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		@Override
		public int getCount() {
			return beans.size();
		}

		@Override
		public Object getItem(int position) {
			return beans.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			ViewHolder holder;

			if (convertView == null) {
				holder = new ViewHolder();
				convertView = inflater.inflate(R.layout.record_lv_item, null);
				holder.english_tv = (TextView) convertView.findViewById(R.id.record_english);
				holder.chinese_tv = (TextView) convertView.findViewById(R.id.record_chinese);
				holder.play_btn = (ImageButton) convertView.findViewById(R.id.play_btn);
				holder.dele_btn = (Button) convertView.findViewById(R.id.dele_btn);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			final NoteBean bean = beans.get(position);
			holder.english_tv.setText(bean.getEnglish());
			holder.chinese_tv.setText(bean.getChinese());
			holder.play_btn.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					showSynDialog(bean.getEnglish());
				}
			});
			holder.dele_btn.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if( btn_state == 1 ){
						copy(bean);
					}else if( btn_state == 2 ){
						mDataBaseUtil.dele(bean.getId());
						beans.remove(position);
						adapter.notifyDataSetChanged();
						ToastUtil.diaplayMesShort(getApplicationContext(), "删除成功");
					}
					
				}
			});
			if( btn_state == 0 ){
				holder.play_btn.setVisibility(View.VISIBLE);
				holder.dele_btn.setVisibility(View.GONE);
			}else if( btn_state == 1 ){
				holder.play_btn.setVisibility(View.GONE);
				holder.dele_btn.setText("复制");
				holder.dele_btn.setVisibility(View.VISIBLE);
			}else if( btn_state == 2 ){
				holder.play_btn.setVisibility(View.GONE);
				holder.dele_btn.setText("删除");
				holder.dele_btn.setVisibility(View.VISIBLE);
			}
			
			return convertView;
		}
	}
	
	private void showMenu(){
		PopDialog mPopDialog = new PopDialog(this,R.style.dialog);
		mPopDialog.setListener(new PopViewItemOnclickListener() {
			
			@Override
			public void onThirdClick(View v) {
				setSate(2);
			}
			
			@Override
			public void onSecondClick(View v) {
				setSate(1);
			}
			
			@Override
			public void onFirstClick(View v) {
				setSate(0);
			}
		});
		mPopDialog.setPopViewPosition();
		mPopDialog.show();
	}
	
	private void setSate(int num){
		btn_state = num;
		adapter.notifyDataSetChanged();
	}
	
	static class ViewHolder {
		private TextView english_tv;
		private TextView chinese_tv;
		private ImageButton play_btn;
		private Button dele_btn;
	}
	
	private void copy(NoteBean bean){
		// 得到剪贴板管理器
		String conent = bean.getEnglish();
		ClipboardManager cmb = (ClipboardManager)this.getSystemService(Context.CLIPBOARD_SERVICE);
		cmb.setText(conent);
		showToast("复制成功");
	}
	
	/**
	 * 弹出合成Dialog，进行语音合成
	 * @param
	 */
	public void showSynDialog(String source)
	{

		if (TextUtils.isEmpty(source)) {
			source = "nothing";
		}
		//设置合成文本.
		ttsDialog.setText(source, null);

		//设置发音人.
		String role = "vimary";//vimary,catherine,henry
		ttsDialog.setVoiceName(role);
		//设置语速.
		int speed = 50;
		ttsDialog.setSpeed(speed);

		//设置音量.
		int volume = 100;
		ttsDialog.setVolume(volume);

		//设置背景音.
		String music = mSharedPreferences.getString(
				getString(R.string.preference_key_tts_music),
				getString(R.string.preference_default_tts_music));
		ttsDialog.setBackgroundSound(music);

		//弹出合成Dialog
		ttsDialog.show();
	}


	@Override
	public void onBufferPercent(int percent,int beginPos,int endPos) {
		mPercentForBuffering = percent;
	}

	@Override
	public void onEnd(SpeechError arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onPlayBegin() {
		// TODO Auto-generated method stub
	}

	@Override
	public void onPlayPaused() {
		// TODO Auto-generated method stub
	}

	@Override
	public void onPlayPercent(int percent,int beginPos,int endPos) {
		mPercentForPlaying = percent;
	}

	@Override
	public void onPlayResumed() {
		
	}
	
	/**
	 * SynthesizerPlayerListener的"停止播放"回调接口.
	 * @param
	 */
	@Override
	protected void onStop() {
		if (null != mSynthesizerPlayer) {
			mSynthesizerPlayer.cancel();
		}
		super.onStop();
	}
	
	private void showToast(String toastString) {
		Toast.makeText(getApplicationContext(), toastString, 0).show();
	}
	@Override
	protected void onDestroy(){  
	    super.onDestroy();  
	    if(mDataBaseUtil!= null){  
	    	mDataBaseUtil.close();
	    }  
	}   

}
